<!-- 系统更新页面 -->
<template>
  <view class="update-page">
    <!-- 页面头部 -->
    <view class="update-header">
      <button class="back-btn" @tap="goBack">← 返回</button>
      <text class="header-title">系统更新</text>
    </view>
    
    <!-- 当前版本信息 -->
    <view class="current-version-info">
      <text class="current-version-text">当前版本：{{ currentVersion }}</text>
      <button class="refresh-btn" @tap="fetchVersionHistory" :disabled="loading">
        {{ loading ? '加载中...' : '刷新' }}
      </button>
    </view>
    
    <!-- 错误提示 -->
    <view v-if="error" class="error-message">
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @tap="fetchVersionHistory">重试</button>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading && !error" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">正在加载更新信息...</text>
    </view>
    
    <!-- 版本更新列表 -->
    <view v-if="!loading && !error && versionList.length > 0" class="version-list">
      <view v-for="version in versionList" :key="version.id" class="version-item">
        <!-- 版本头部 -->
        <view class="version-header">
          <view class="version-info">
            <text class="version-number">{{ version.version }}</text>
            <text class="version-date">{{ formatDate(version.releaseDate) }}</text>
          </view>
          <view v-if="version.forceUpdate" class="force-update-tag">强制更新</view>
        </view>
        
        <!-- 更新内容 -->
        <view class="update-content">
          <view v-for="(line, index) in getUpdateLines(version.changeLog)" :key="index" class="update-line">
            • {{ line }}
          </view>
        </view>
        
        <!-- 下载按钮 -->
        <view v-if="version.downloadUrl" class="download-section">
          <button class="download-btn" @tap="downloadUpdate(version)">
            下载更新
          </button>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view v-if="!loading && !error && versionList.length === 0" class="empty-state">
      <text class="empty-text">暂无系统更新</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { NETWORK_CONFIG } from '@/config/network.js'

// 响应式数据
const currentVersion = ref('1.0.0');
const versionList = ref([]);
const loading = ref(false);
const error = ref('');
const fetchingVersion = ref(false);

// 后端API配置（改为动态）
const API_BASE_URL = NETWORK_CONFIG.API_BASE_URL;

// 获取当前应用版本号
const fetchCurrentVersion = async () => {
  fetchingVersion.value = true;
  try {
    // 首先尝试从应用信息获取当前版本
    let appVersion = '1.0.0';
    
    // 尝试获取小程序版本信息
    try {
      const accountInfo = uni.getAccountInfoSync && uni.getAccountInfoSync();
      if (accountInfo && accountInfo.miniProgram && accountInfo.miniProgram.version) {
        appVersion = accountInfo.miniProgram.version;
      }
    } catch (e) {
      console.log('无法获取小程序版本信息，使用默认版本');
    }
    
    // 尝试获取APP版本信息
    try {
      const systemInfo = uni.getSystemInfoSync && uni.getSystemInfoSync();
      if (systemInfo && systemInfo.appVersion) {
        appVersion = systemInfo.appVersion;
      }
    } catch (e) {
      console.log('无法获取APP版本信息，使用默认版本');
    }
    
    // 获取最新版本信息
    try {
      const response = await uni.request({
        url: `${API_BASE_URL}/version/latest`,
        method: 'GET',
        timeout: 10000
      });

      if (response.statusCode === 200 && response.data) {
        const result = response.data;
        if (result.code === 200 && result.data) {
          // 显示最新版本号
          currentVersion.value = result.data.version;
          console.log('显示最新版本:', result.data.version);
        } else {
          // 如果获取最新版本失败，使用本地版本
          currentVersion.value = appVersion;
        }
      } else {
        // 如果API调用失败，使用本地版本
        currentVersion.value = appVersion;
      }
    } catch (err) {
      console.log('获取最新版本失败，使用本地版本:', err);
      currentVersion.value = appVersion;
    }
    
    // 检查是否有新版本可用（用于更新提示）
    try {
      const checkResponse = await uni.request({
        url: `${API_BASE_URL}/version/check`,
        method: 'GET',
        data: { currentVersion: appVersion },
        timeout: 10000
      });

      if (checkResponse.statusCode === 200 && checkResponse.data) {
        const result = checkResponse.data;
        if (result.code === 200 && result.data) {
          // 有新版本可用，可以在这里显示更新提示
          console.log('发现新版本:', result.data.version);
        }
      }
    } catch (err) {
      console.log('检查更新失败:', err);
    }
  } catch (err) {
    console.log('获取版本信息失败:', err);
    currentVersion.value = '1.0.0';
  } finally {
    fetchingVersion.value = false;
  }
};

// 获取版本历史列表
const fetchVersionHistory = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    const response = await uni.request({
      url: `${API_BASE_URL}/version/history`,
      method: 'GET',
      timeout: 10000,
      header: {
        'Content-Type': 'application/json'
      }
    });
    
    if (response.statusCode === 200 && response.data) {
      const result = response.data;
      if (result.code === 200 && result.data) {
        // 数据已经按时间倒序排列（后端已处理）
        versionList.value = result.data;
      } else {
        error.value = result.message || '获取版本信息失败';
      }
    } else {
      error.value = '网络请求失败';
    }
  } catch (err) {
    console.error('获取版本信息失败:', err);
    error.value = '获取版本信息失败，请检查网络连接';
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  try {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (e) {
    return dateString;
  }
};

// 处理更新日志，按换行符分割
const getUpdateLines = (changeLog) => {
  if (!changeLog) return [];
  return changeLog.split('\n').filter(line => line.trim() !== '');
};

// 下载更新
const downloadUpdate = (version) => {
  if (version.downloadUrl) {
    uni.showModal({
      title: '下载更新',
      content: `确定要下载 ${version.version} 版本吗？`,
      confirmText: '下载',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 显示下载提示
          uni.showToast({
            title: '正在跳转下载页面...',
            icon: 'none'
          });
          
          // 模拟跳转下载页面
          setTimeout(() => {
            console.log('跳转到下载页面:', version.downloadUrl);
            
            // 如果是强制更新，显示特殊提示
            if (version.forceUpdate) {
              uni.showModal({
                title: '强制更新提醒',
                content: '此版本为强制更新，请务必完成更新以确保系统正常运行。',
                showCancel: false,
                confirmText: '知道了'
              });
            }
          }, 1000);
        }
      }
    });
  }
};

// 页面加载时执行
onMounted(async () => {
  // 获取当前应用版本号
  await fetchCurrentVersion();
  
  // 获取版本历史
  fetchVersionHistory();
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped>
.update-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f2f5 0%, #ffffff 100%);
  padding: 0 1rem 2rem 1rem;
}

/* 页面头部 */
.update-header {
  width: 100%;
  height: 3.5rem;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  border-radius: 0 0 20px 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-bottom: 2rem;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.back-btn {
  position: absolute;
  left: 1rem;
  background: none;
  border: none;
  color: #fff;
  font-size: 1.1rem;
  padding: 0.5rem;
  border-radius: 6px;
  transition: background 0.2s;
}

.back-btn:active {
  background: rgba(255, 255, 255, 0.2);
}

.header-title {
  color: #fff;
  font-size: 1.4rem;
  font-weight: 600;
}

/* 当前版本信息 */
.current-version-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  padding: 1rem 1.5rem;
  border-radius: 12px;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.current-version-text {
  font-size: 1rem;
  color: #333;
  font-weight: 500;
}

.refresh-btn {
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 0.5rem 1rem;
  font-size: 0.9rem;
  transition: background 0.2s;
}

.refresh-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.refresh-btn:not(:disabled):active {
  background: #096dd9;
}

/* 错误提示 */
.error-message {
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.error-text {
  color: #cf1322;
  font-size: 0.9rem;
}

.retry-btn {
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 0.4rem 0.8rem;
  font-size: 0.8rem;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 3rem 1rem;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #666;
  font-size: 0.9rem;
}

/* 版本列表 */
.version-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.version-item {
  background: #fff;
  border-radius: 16px;
  padding: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.version-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1rem;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.version-info {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}

.version-number {
  font-size: 1.2rem;
  font-weight: 700;
  color: #1890ff;
}

.version-date {
  font-size: 0.85rem;
  color: #666;
}

.force-update-tag {
  background: #ff4d4f;
  color: #fff;
  padding: 0.3rem 0.8rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 600;
}

/* 更新内容 */
.update-content {
  margin-bottom: 1rem;
}

.update-line {
  font-size: 0.95rem;
  color: #333;
  line-height: 1.6;
  margin-bottom: 0.5rem;
  padding-left: 0.5rem;
}

/* 下载部分 */
.download-section {
  display: flex;
  justify-content: flex-end;
  padding-top: 1rem;
  border-top: 1px solid #f0f0f0;
}

.download-btn {
  background: #52c41a;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 0.6rem 1.2rem;
  font-size: 0.9rem;
  transition: background 0.2s;
}

.download-btn:active {
  background: #389e0d;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 3rem 1rem;
}

.empty-text {
  color: #999;
  font-size: 1rem;
}
</style>
